package com.san.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.san.app.domain.InspectDO;
import com.san.app.domain.InspectResultDO;
import com.san.app.service.InspectResultService;
import com.san.app.service.InspectService;
import com.san.app.vo.InspectHisAllVo;
import com.san.app.vo.InspectHisCheckedVo;
import com.san.app.vo.InspectHisVo;
import com.san.app.vo.InspectVO;
import com.san.base.controller.BaseController;
import com.san.common.annotation.Log;
import com.san.common.utils.ExcelUtil;
import com.san.common.utils.ExportExcelUtil;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.R;
/**
 * 信用核查控制层
 * @author SuperSR
 * @date 2019年3月26日 上午10:19:44
 *
 */
@Controller
@RequestMapping("/app/inspect")
public class InspectController extends BaseController{

	@Autowired
	private InspectService inspectService;
	@Autowired
	private InspectResultService inspectResultService;
	
	private static final Logger logger = LoggerFactory.getLogger(InspectController.class);
	
	private String PREFIX = "app/inspect";
	
	@GetMapping("")
	@RequiresPermissions("app:inspect:view")
	String source(Model model) {
		return PREFIX + "/view";
	}

	@GetMapping("/list")
	@RequiresPermissions("app:inspect:view")
	@ResponseBody
	public PageUtils findCreditCommitment(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			Query query = new Query(params);
			List<InspectDO> list = inspectService.list(query);
			int total = inspectService.count(query);
			pageUtils = new PageUtils(list, total);
		} catch (Exception e) {
			logger.error("获取信用核查列表出错",e);
		}
		return pageUtils;
	}
	
	/**
	 * 进入新增页面
	 * @return
	 */
	@GetMapping("/add")
	@RequiresPermissions("app:inspect:add")
	String add() {
		return PREFIX + "/add";
	}
	
	/**
	 * 保存新增信用核查
	 * @param inspectVO
	 * @return
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("app:inspect:add")
	@Log("新增信用核查")
	public R save(InspectVO inspectVO) {
		try{
			int state = inspectService.save(inspectVO);
			if(state == -1){
				return R.error("该信用核查已经存在");
			}else if (state > 0) {
				return R.ok();
			}
		} catch(Exception e) {
			logger.error("新增信用核查失败");
		}
		return R.error();
	}
	
	/**
	 * 进入编辑页面
	 * @return
	 */
	@GetMapping("/edit/{inspectId}")
	@RequiresPermissions("app:inspect:edit")
	String edit(@PathVariable("inspectId") Long inspectId,Model model) {
		InspectDO inspect = inspectService.getById(inspectId);
		model.addAttribute("inspect",inspect);
		return PREFIX + "/edit";
	}
	
	/**
	 * 修改信用核查
	 * @param inspectVO
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/doEdit")
	@RequiresPermissions("app:inspect:edit")
	@Log("修改信用核查")
	public R doEdit(InspectVO inspectVO) {
		try{
			int state = inspectService.doEdit(inspectVO);
			if(state == -1){
				return R.error("该信用核查已经存在");
			}else if(state > 0){
				return R.ok();
			}
		} catch(Exception e) {
			logger.error("修改信用核查失败");
		}
		return R.error();
	}
	
	/**
	 * 删除信用核查
	 * @param id
	 * @return
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("app:inspect:remove")
	@Log("删除信用核查")
	public R remove(Long id){
		try{
			int state = inspectService.remove(id);
			if(state > 0){
				return R.ok();
			}else if(state == -1){
				return R.ok("该核查模板存在核查项，不可删除");
			}
		} catch(Exception e) {
			logger.error("删除信用核查失败",e);
		}
		return R.error();
	}
	
	/**
	 * 批量删除信用核查
	 * @param ids
	 * @return
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("app:inspect:batchRemove")
	@Log("批量删除信用核查")
	public R remove(@RequestParam("ids[]") Long[] ids) {
		try {
			int state = inspectService.batchRemove(ids);
			if(state > 0){
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("批量删除信用核查失败",e);
		}
		return R.error();
	}
	
	/**
	 * 进入核查页面
	 * @return
	 */
	@GetMapping("/check/{inspectId}")
	@RequiresPermissions("app:inspect:check")
	String check(@PathVariable("inspectId") Long inspectId,Model model) {
		InspectDO inspect = inspectService.getById(inspectId);
		model.addAttribute("inspect",inspect);
		return PREFIX + "/check";
	}
	
	/**
	 * 信用核查
	 * @param inspectVO
	 * @return
	 */
	@ResponseBody
	@PostMapping("/doCheck")
	@RequiresPermissions("app:inspect:check")
	@Log("信用核查")
	public R doCheck(@RequestParam(value="inspectId",required=false)Long inspectId,@RequestParam(value="excelFile",required=false)MultipartFile file,HttpServletRequest request,HttpServletResponse response) {
		try{
			MultipartRequest multipartRequest = (MultipartRequest)request;
			MultipartFile excelFile = multipartRequest.getFile("excelFile");
			Long userId = getUserId();
			if(excelFile != null){
				String fileName = excelFile.getOriginalFilename();
				String type = fileName.substring(fileName.lastIndexOf(".")+1);
				if("xlsx".equals(type) || "xls".equals(type)){
					List<List<String>> datas = ("xlsx".equals(type) ? ExcelUtil.readXlsx(excelFile.getInputStream()) : ExcelUtil.readXls(excelFile.getInputStream()));
					//读取的内容后处理
					if(datas !=null && datas.size()>0){
						inspectService.runCheck(inspectService, datas, inspectId,response,userId);
						//List<Object> list = inspectService.doCheck(datas,inspectId);
						return R.ok();
					}
				}else{
					return R.error("请导入Excel文件");
				}
			}
		} catch(Exception e) {
			logger.error("匹配核查模板失败",e);
		}
		return R.error();
	}
	
	@GetMapping("/download/{inspectId}")
	@RequiresPermissions("app:inspect:download")
	String view(Model model,@PathVariable("inspectId") Long inspectId) {
		model.addAttribute("inspectId",inspectId);
		return PREFIX + "/download";
	}
	
	@GetMapping("/downloadList")
	@RequiresPermissions("app:inspect:download")
	@ResponseBody
	public PageUtils downloadList(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			Query query = new Query(params);
			List<InspectResultDO> list = inspectResultService.list(query);
			//int total = .count(query);
			pageUtils = new PageUtils(list, list.size());
			/*Query query = new Query(params);
			List<InspectDO> list = inspectService.list(query);
			int total = inspectService.count(query);
			pageUtils = new PageUtils(list, total);*/
		} catch (Exception e) {
			logger.error("获取下载结果列表出错",e);
		}
		return pageUtils;
	}
	
	@GetMapping("/downFile")
	@RequiresPermissions("app:inspect:download")
	@Log("下载核查结果文件")
	public void downFile(String fileName,HttpServletResponse response) {
		try{
			inspectService.downFile(fileName,response);	
		} catch(Exception e) {
			logger.error("下载核查结果文件失败",e);
		}
	}
	
	/*@ResponseBody
	@GetMapping("/download/{fileName}")
	void download(@PathVariable("fileName") String fileName, HttpServletResponse res) {
		res.setHeader("content-type", "application/octet-stream");
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
		File path = null;
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			path = new File(ResourceUtils.getURL("classpath:").getPath());
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(path + "/excel/" + fileName + ".xls")));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}*/

	
	/**
	 * 信用核查
	 * @param inspectVO
	 * @return
	 */
	/*@ResponseBody
	@PostMapping("/doCheck")
	@RequiresPermissions("app:inspect:check")
	@Log("信用核查")
	public R doCheck(Long inspectId,MultipartFile excelFile,HttpServletRequest request) {
		try{
			MultipartRequest multipartRequest = (MultipartRequest)request;
			MultipartFile file = multipartRequest.getFile("excelFile");
			return R.ok();
		} catch(Exception e) {
			logger.error("匹配核查模板失败",e);
		}
		return R.error();
	}*/
	
	
	/**
	 * 跳转核实历史页面
	 * @param inspectId
	 * @param model
	 * @return
	 */
	@GetMapping("/history/{inspectId}")
	@RequiresPermissions("app:inspect:check")
	String history(@PathVariable("inspectId") Long inspectId,Model model) {	
		InspectDO inspect = inspectService.getById(inspectId);
		model.addAttribute("inspect",inspect);
		return PREFIX + "/history";
	}
	
	/**
	 * 跳转核实成功的展示界面
	 * @param inspectId
	 * @param model
	 * @return
	 */
	@GetMapping("/historychecked/{batchNo}")
	@RequiresPermissions("app:inspect:check")
	String historychecked(@PathVariable("batchNo") String batchNo,Model model) {	
		/*InspectDO inspect = inspectService.getById(inspectId);*/
		model.addAttribute("batchNo",batchNo);
		return PREFIX + "/historychecked";
	}
	
	/**
	 * 跳转详细核实企业的页面
	 * @param inspectId
	 * @param model
	 * @return
	 */
	@GetMapping("/historyList/{batchNo}")
	@RequiresPermissions("app:inspect:check")
	String historyList(@PathVariable("batchNo") String batchNo,Model model) {	
		model.addAttribute("batchNo",batchNo);
		return PREFIX + "/historyList";
	}
	/**
	 * 获取核实历史界面
	 * @param inspectId
	 * @param model
	 * @return
	 */
	@GetMapping("/checkHistory")
	@RequiresPermissions("app:inspect:check")
	@ResponseBody
	@Log("信用核查历史")
	public PageUtils checkHistory(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			Query query = new Query(params);
			List<InspectHisVo> list = inspectService.hislist(query);
			int total = inspectService.hiscount(query);
			pageUtils = new PageUtils(list, total);
		} catch (Exception e) {
			logger.error("获取信用核查列表出错",e);
		}
	
		return pageUtils;
		
	}
	
	@GetMapping("/historycheckedList")
	@RequiresPermissions("app:inspect:check")
	@ResponseBody
	@Log("核实成功展示")
	public PageUtils historycheckedList(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			Query query = new Query(params);
			List<InspectHisCheckedVo> list = inspectService.historycheckedList(query);
			int total = inspectService.historycheckedListCount(query);
			pageUtils = new PageUtils(list, total);
		} catch (Exception e) {
			logger.error("获取信用核查列表出错",e);
		}
	
		return pageUtils;
		
	}

	@GetMapping("/historyallList")
	@RequiresPermissions("app:inspect:check")
	@ResponseBody
	@Log("核实企业展示")
	public PageUtils historyallList(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			Query query = new Query(params);
			List<InspectHisAllVo> list = inspectService.historyallList(query);
			int total = inspectService.historyallListCount(query);
			pageUtils = new PageUtils(list, total);
		} catch (Exception e) {
			logger.error("获取信用核查列表出错",e);
		}
	
		return pageUtils;
		
	}
	
	@SuppressWarnings("unchecked")
	@GetMapping("/exportHistory/{batchNo}")
	@RequiresPermissions("app:inspect:download")
	@Log("导出核实记录")
	public void exportHistory(@PathVariable("batchNo") String batchNo) {
		try{
			Map params=new HashMap<String,String>();
			params.put("batchNo",batchNo);
			Query query = new Query(params);
			List list = inspectService.historyallList(query);
			List totalList=new ArrayList();
			for(int i=0;i<list.size();i++) {
				//List hislist=new ArrayList();
				Object obj[]=new Object[4];
				InspectHisAllVo vo=(InspectHisAllVo) list.get(i);
				obj[0]=vo.getFrmc();
				obj[1]=vo.getTyshxydm();
				obj[2]=vo.getIsBdcg();
				obj[3]=vo.getIsValid();
				totalList.add(obj);
			}
			String rownum[]={"法人名称","统一社会信用代码","比对成功数","核实成功数"};
			ExportExcelUtil excel=new ExportExcelUtil("核实结果",rownum,totalList);
			excel.export();
		} catch(Exception e) {
			logger.error("下载核查结果文件失败",e);
		}
	}
}
